package com.codejiwei.flink.practice;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SessionWindowTimeGapExtractor;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author jiwei
 * @description 会话窗口 可以是固定gap；也可以是动态gap
 * @date 2023/5/23 10:50
 */
public class Flink_Windows_Session {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(10);

        env.socketTextStream("localhost", 8889)
                .flatMap((String line, Collector<Tuple2<String, Long>> out) ->
                    Arrays.stream(line.split("\\W+")).forEach(word -> out.collect(Tuple2.of(word, 1L))))
                .returns(Types.TUPLE(Types.STRING, Types.LONG))
//                .windowAll(ProcessingTimeSessionWindows.withGap(Time.seconds(10)))
//                .reduce((value1, value2) -> {
//                    return Tuple2.of(value1.f0 + "_" + value2.f0 , 1L);
//                })
                .keyBy(t -> t.f0)
//                .window(ProcessingTimeSessionWindows.withGap(Time.minutes(10)))
                .window(ProcessingTimeSessionWindows.withDynamicGap(new SessionWindowTimeGapExtractor<Tuple2<String, Long>>() {
                    @Override
                    public long extract(Tuple2<String, Long> stringLongTuple2) {
                        return stringLongTuple2.f0.length() * 1000;
                    }
                }))
                .sum(1)
                .print();

        env.execute();
    }
}
